package com.example.ormsqlsplicingframe1.utlis;

import io.swagger.annotations.ApiModel;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@ApiModel("获取list泛型")
public class GetGenerics {

    public static Class getListGenerate(Field field) {
        if (field.getType() == List.class) {
            Type genericType = field.getGenericType();
            if (genericType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericType;
                // 得到泛型里的class类型对象
                Class<?> actualTypeArgument = (Class<?>) pt.getActualTypeArguments()[0];
                return actualTypeArgument;
            }
        }else {


            return field.getType();
        }
        return null;
    }

    //根据list泛型 返回对应的值
    public static Object typeReturn(Class generate,String value){


        if (generate ==  String.class) return value;
        if (generate == Long.class) return Long.parseLong(value);
        if (generate == Integer.class) return Integer.parseInt(value);

        throw new RuntimeException("当前list泛型不包含"+generate);
    }

    //从obj获取值
    public static List<Object> objToList(Object obj){
        List<Object> result = new ArrayList<>();
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                result.add(o);
            }
        }
        return result;
    }

    //把数组变成一个
    public static Object listChangeSingle(Object obj){
        StringJoiner stringJoiner = new StringJoiner(",");
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                stringJoiner.add(String.valueOf(o));
            }
        }

        return stringJoiner.toString();
    }
}
